package com.yxx.config;

import cn.hutool.core.lang.hash.Hash;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义缓存过期时间
 * @author yuxiangxun
 * @date 2024/9/27
 * @apiNote
 */
@Configuration
@EnableCaching
public class CacheConfig {
    @Bean("cacheManager_config")
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory ){
        if (redisConnectionFactory == null) {
            throw new IllegalArgumentException("RedisConnectionFactory is null");
        }

        // 默认过期时间 30 分钟
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(30))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));

        Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
        // 自定义过期时间 30 分钟
        cacheConfigurations.put("setmedicineCache", RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMinutes(30)));

        return RedisCacheManager.builder(redisConnectionFactory)
                .cacheDefaults(defaultCacheConfig)
                .withInitialCacheConfigurations(cacheConfigurations)
                .build();
    }
}
